package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;
@Service
@Slf4j
public class ApUserLoginServiceImpl implements ApUserLoginService {
    @Autowired
    ApUserMapper apUserMapper;

  @Override
  public ResponseResult login(LoginDTO dto) {
    String phone = dto.getPhone(); // 电话
    String password = dto.getPassword(); // 密码
    Integer equipmentId = dto.getEquipmentId(); // 设备id
    if (equipmentId == null) {
      CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "设备id不存在");
    }
    // 不登录 没有phone ,password ,有equipmentID
    if (StringUtils.isBlank(phone) && StringUtils.isBlank(password)) {
      // 通过设备ID登录的 userId存0
      Map<String, Object> map = new HashMap<>();
      String token = AppJwtUtil.getToken(0L);
      map.put("token", token);
      return ResponseResult.okResult(map);

    } else {
      // 登录， 有phone ,password ,equipmentID
      LambdaQueryWrapper<ApUser> wrapper = Wrappers.lambdaQuery();
      wrapper.eq(ApUser::getPhone, phone);
      // 查询用户
      ApUser apUser = apUserMapper.selectOne(wrapper);
      if (apUser == null) {
        CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
      }
      String userPassword = apUser.getPassword();
      String salt = apUser.getSalt();
      // 对前端传来的密码进行md5加密，
      String newPwd = DigestUtils.md5DigestAsHex((password + salt).getBytes());
      if (!newPwd.equals(userPassword)) {
        CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "密码错误");
      }
      // 检查用户的状态是否正确
      Boolean status = apUser.getStatus();
      if (status) {
        CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR, "用户状态被锁定");
      }
      //  颁发token,将token，还有user发给浏览器，让浏览器保存
      String token = AppJwtUtil.getToken(apUser.getId().longValue());
      Map<String, Object> map = new HashMap<>();
      apUser.setPassword(null);
      apUser.setSalt(null);
      map.put("token", token);
      map.put("user", apUser);
      return ResponseResult.okResult(map);
    }
      }

}
